package com.vvv.method;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author vvv
 * @date 2023-10-25 10 51
 * discription
 */
public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        Container container = new Container();
        new Thread(() -> {
            container.read();
        }).start();
        new Thread(() -> {
            container.write(111);
        }).start();
    }
}
class Container {
    private Object data;
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public Object read() {
        readLock.lock();
        System.out.println("获取读锁成功");
        try {
            System.out.println("read read read");
            Thread.sleep(1000);
            return data;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            readLock.unlock();
            System.out.println("释放读锁成功");
        }
    }

    public void write(Object data) {
        writeLock.lock();
        System.out.println("获取写锁成功");
        try {
            System.out.println("write write write");
            this.data = data;
        } finally {
            writeLock.unlock();
            System.out.println("释放写锁成功");
        }
    }
}
